/**
 * @author Eduardo Leonne Souza de Oliveira
 * @version 1.0
 * Date: 2011-12-29
 * Last change: 2011-12-29 
 * 
 */

package com.leonne.harpacristabrasileira.activities;

import java.util.ArrayList;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.util.FloatMath;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.leonne.harpacristabrasileira.R;
import com.leonne.harpacristabrasileira.dao.AnthemsDAO;
import com.leonne.harpacristabrasileira.dao.VersesDAO;
import com.leonne.harpacristabrasileira.lists.vo.AnthemVO;
import com.leonne.harpacristabrasileira.lists.vo.VerseVO;
import com.leonne.harpacristabrasileira.tools.DataCache;
import com.leonne.harpacristabrasileira.tools.MyConstants;
import com.leonne.harpacristabrasileira.tools.Utils;

public class TextContentPageActivity extends GenericActivity implements OnGestureListener, OnCompletionListener {

	Matrix matrix = new Matrix();
	Matrix savedMatrix = new Matrix();

	// We can be in one of these 3 states
	static final int NONE = 0;
	static final int DRAG = 1;
	static final int ZOOM = 2;
	private int mode = NONE;
	private float oldDist;
	private PointF mid = new PointF();

	private RelativeLayout rl;
	private RelativeLayout player;
	private ArrayList<VerseVO> verses;
	private TextView tvArray[];
	private TextView edtNumber;
	private TextView edtTitle;
	private TextView playerTitle;
	private ImageView imgIsFavorite;
	private ScrollView sv;
	private GestureDetector gestureScanner;
	private float xDown = 0;
	private float yDown = 0;
	private float fontSize;

	/**
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (Utils.isWideScreen(this.getBaseContext()))
        	setContentView(R.layout.text_content_page_wide);
        else
        	setContentView(R.layout.text_content_page);
		
		this.gestureScanner = new GestureDetector(this);
		this.rl = (RelativeLayout) findViewById(R.id.rootLayoutTextContentPage);
		this.player = (RelativeLayout) findViewById(R.id.contentPlayerLayout);
		this.edtNumber = (TextView) findViewById(R.id.anthemContentNumber);
		this.edtTitle = (TextView) findViewById(R.id.anthemContentTitle);
		this.imgIsFavorite = (ImageView) findViewById(R.id.imgFavorite);
		this.sv = (ScrollView) findViewById(R.id.scrContent);
		this.playerTitle = (TextView) findViewById(R.id.contentTitlePlayer);
		initiateGeneralMediaPlayer();
		this.generalMediaPlayer.setOnCompletionListener(this);
		if (this.generalMediaPlayer.isPlaying()){
			this.player.setVisibility(View.VISIBLE);
			this.playerTitle.setText(String.valueOf(MyConstants.idAnthemIsPlaying) + ". " + MyConstants.titleAnthemIsPlaying);
		}
		
		if (Utils.isTabletDevice(this.getBaseContext()))
			this.fontSize = MyConstants.FONTSIZESTABLET[MyConstants.SELECTEDFONTSIZE];
		else
			this.fontSize = MyConstants.FONTSIZES[MyConstants.SELECTEDFONTSIZE];

		Bundle extras = this.getIntent().getExtras();
		this.idAnthem = extras.getInt("IDANTHEM");

		this.loadData();
		int isFavorite = ((VerseVO) this.verses.get(0)).getIsFavorite();
		if (isFavorite == 1){
			this.imgIsFavorite.setImageResource(R.drawable.favoritestar);
			this.imgIsFavorite.setTag("1");
		}
		
		this.imgIsFavorite.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				ImageView iv = (ImageView) v;
				AnthemsDAO dao = new AnthemsDAO(getBaseContext());
				int resource;
				String value;
				if (iv.getTag().equals("1")){
					resource = R.drawable.notfavoritestar;
					value = "0";
				} else {
					resource = R.drawable.favoritestar;
					value = "1";
				}
				String sql = "UPDATE anthems SET isfavorite="+ value +" WHERE idanthem = " + idAnthem;
				dao.execSql(sql);
				
				iv.setImageResource(resource);
				iv.setTag(value);
				
				int index = 0;
				if (DataCache.anthemsCache.size() == 640)
					index = idAnthem-1;
				else {
					for (int i = 0;i < DataCache.anthemsCache.size();i++){
						AnthemVO tmp = (AnthemVO) DataCache.anthemsCache.get(i);
						if (tmp.getIdAnthem() == idAnthem){
							index = i;
							break;
						}
					}
				}
				AnthemVO anthem = (AnthemVO) DataCache.anthemsCache.get(index);
				anthem.setIsFavorite(Integer.parseInt(value));
			}
		});

		this.sv.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction() & MotionEvent.ACTION_MASK) {
					case MotionEvent.ACTION_UP:
						float newX = event.getX();
						float newY = event.getY();
						float difX = xDown - newX;
						if (difX < 0)
							difX = difX * -1;
						float difY = yDown - newY;
						if (difY < 0)
							difY = difY * -1;
						if (difX > difY)
							return gestureScanner.onTouchEvent(event);
						else
							return false;
					case MotionEvent.ACTION_DOWN:
						xDown = event.getX();
						yDown = event.getY();
						return false;
					case MotionEvent.ACTION_POINTER_DOWN:
						oldDist = spacing(event);
						if (oldDist > 10f) {
							savedMatrix.set(matrix);
							midPoint(mid, event);
							mode = ZOOM;
						}
						break;
					case MotionEvent.ACTION_POINTER_UP:
						mode = NONE;
						return false;
					case MotionEvent.ACTION_MOVE:
						if (mode == ZOOM) {
							float newDist = spacing(event);
							if (newDist > 10f) {
								matrix.set(savedMatrix);
								float scale = newDist / oldDist;
								matrix.postScale(scale, scale, mid.x, mid.y);
								//Zoom in
								if (newDist > oldDist){
									updateElementsFont(true);
								} else { // Zoom out
									updateElementsFont(false);
								}
							}
							return false;
						} else
							return gestureScanner.onTouchEvent(event);
				}
				return gestureScanner.onTouchEvent(event);
			}
		});
		this.playerTitle.setSelected(true);
	}

	private float spacing(MotionEvent event) {
		float x = event.getX(0) - event.getX(1);
		float y = event.getY(0) - event.getY(1);
		return FloatMath.sqrt(x * x + y * y);
	}

	private void midPoint(PointF point, MotionEvent event) {
		float x = event.getX(0) + event.getX(1);
		float y = event.getY(0) + event.getY(1);
		point.set(x / 2, y / 2);
	}
	
	private void updateElementsFont(boolean flag){
		int minFontSize = (Utils.isTabletDevice(this.getBaseContext())) ? MyConstants.FONTSIZESTABLET[MyConstants.SELECTEDFONTSIZE] : MyConstants.FONTSIZES[MyConstants.SELECTEDFONTSIZE];
		int maxFontSize = (Utils.isTabletDevice(this.getBaseContext())) ? MyConstants.FONTSIZESTABLET[3] : MyConstants.FONTSIZES[3];
		float proportion = (Utils.isTabletDevice(this.getBaseContext())) ? 0.6f : 0.2f;
		if (flag){
			if (this.fontSize > maxFontSize)
				return;
			this.fontSize += proportion;
		} else {
			if (this.fontSize <= minFontSize)
				return;
			this.fontSize -= proportion;
		}
		for (int i = 0;i < this.tvArray.length;i++)
			this.tvArray[i].setTextSize(this.fontSize);
	}

	private void cleanData() {
		this.rl.removeAllViews();
		this.tvArray = null;
	}

	private void loadData() {
		this.cleanData();
		VersesDAO dao = new VersesDAO(getBaseContext());
		this.verses = dao.fetchByAnthem(idAnthem);

		this.tvArray = new TextView[this.verses.size()];
		VerseVO obj = (VerseVO) this.verses.get(0);
		this.edtNumber.setText(String.valueOf(this.idAnthem) + ". ");
		this.edtTitle.setText(obj.getTitle());

		for (int i = 0; i < this.verses.size(); i++) {
			VerseVO v = (VerseVO) this.verses.get(i);
			this.tvArray[i] = this.createTextView(v.getVerse(),
					v.getIsMainVerse());
			this.tvArray[i].setId(i + 1);
			if (i != 0)
				this.setRelativeLayout(i + 1, i, RelativeLayout.BELOW);
			else
				this.setRelativeLayout(i + 1, this.edtTitle.getId(),
						RelativeLayout.BELOW);
			this.rl.addView(this.tvArray[i]);
		}
	}

	private TextView createTextView(String text, int isMainVerse) {
		TextView tv = new TextView(this);
		tv.setBackgroundColor(android.graphics.Color.TRANSPARENT);
		tv.setText(text);
		tv.setTextSize(this.fontSize);
		if (isMainVerse == 1) {
			tv.setTextColor(Color.parseColor("#CD5C5C"));
			tv.setTypeface(null, Typeface.ITALIC);
			tv.setPadding(40, 0, 15, 0);
		} else {
			tv.setTextColor(Color.parseColor("#000000"));
			tv.setPadding(20, 0, 5, 0);
		}
		return tv;
	}

	private void setRelativeLayout(int acualId, int previousId, int position) {
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.WRAP_CONTENT,
				RelativeLayout.LayoutParams.WRAP_CONTENT);
		lp.setMargins(20, 0, 20, 0);
		if (position != -1)
			lp.addRule(position, previousId);
		this.tvArray[acualId - 1].setLayoutParams(lp);
	}

	@Override
	public boolean onTouchEvent(MotionEvent me) {
		return gestureScanner.onTouchEvent(me);
	}

	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return true;
	}

	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		try {
			if (Math.abs(velocityX) > Math.abs(velocityY)) {
				int ini;
				int end;
				Class<?> obj = TextContentPageActivity.class;
				if (velocityX < 0) {
					this.idAnthem++;
					ini = R.anim.push_left_in;
					end = R.anim.push_left_out;
					obj = (this.idAnthem != 641) ? TextContentPageActivity.class : FirstPageActivity.class;
				} else {
					this.idAnthem--;
					ini = R.anim.push_right_in;
					end = R.anim.push_right_out;
					obj = (this.idAnthem != 0) ? TextContentPageActivity.class : FirstPageActivity.class;
				}

				Intent intent = new Intent(TextContentPageActivity.this, obj);
				intent.putExtra("IDANTHEM", this.idAnthem);
				intent.putExtra("FORCESEARCH", MyConstants.ISFAVORITE);
	    		MyConstants.ISFAVORITE = false;
				startActivity(intent);
				overridePendingTransition(ini, end);
				return true;
			} else {
				if (velocityY > 0) {
					Intent intent = new Intent(TextContentPageActivity.this, FirstPageActivity.class);
					intent.putExtra("FORCESEARCH", MyConstants.ISFAVORITE);
		    		MyConstants.ISFAVORITE = false;
					startActivity(intent);
					overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
				}
				return true;
			}
		} catch (Exception e) {
			e.getMessage();
			return false;
		}
	}

	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	public void onCompletion(MediaPlayer mp) {
		this.player.setVisibility(View.GONE);		
	}
}